package org.vincen.helloworld.javassist;

import java.io.IOException;

import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;

public class PracticeJavassist {
	
	public static void main(String[] args) {
		ClassPool pool = ClassPool.getDefault();
		try {
			CtClass cc = pool.get("org.vincen.helloworld.javassist.BookDao");
			CtMethod cm = cc.getDeclaredMethod("add");
			//此处插入方法，可以加上{}，语句做为字符串拼接
			cm.setBody("{System.out.println(\"add a book...\");}");
			cm.insertBefore("System.out.println(\"start...\");");
			//此处替换BookDao的父类
			cc.setSuperclass(pool.get("org.vincen.helloworld.javassist.AnotherDao"));
			//注意此处写出时的路径
			cc.writeFile("target\\classes");
			Class<?> c = cc.toClass();
			BookDao dao = (BookDao)c.newInstance();
			dao.add();
		} catch (NotFoundException e) {
			e.printStackTrace();
		} catch (CannotCompileException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

class BookDao extends Dao{
	public void add() {
		System.out.println("insert a book...");
	}
}

class Dao {
	public void add(){}
	public void update(){}
	public void delete(){}
	public void find(){}
}

class AnotherDao {
	
}